import CSSMotion from 'rc-motion';
import React, { useRef } from 'react';
import type { ContentProps } from '../../interface';
import Panel from './Panel';

const Content: React.FC<ContentProps> = (props) => {
  const {
    open,
    motionName,
    destroyOnClose,
    forceRender,
    onVisibleChanged,
    ariaId,
    mousePosition,
    styles,
    classNames,
    ...restProps
  } = props;

  const dialogRef = useRef<HTMLDivElement>(null);
  const [transformOriginStyle, setTransformOriginStyle] = React.useState<
    Record<string, string>
  >({});

  function onPrepare() {
    if (!dialogRef.current) return;
    // Panel动画原点设置
    setTimeout(() => {
      // 虽然dialogRef.current 但是立马获取getBoundingClientRect()值有可能为0
      const elementOffset = dialogRef.current!.getBoundingClientRect(); //left/top:距离视口的距离
      // console.log('--dialogRef.current--elementOffset--:', elementOffset);
      // transform-origin 默认以元素的中心点为原点
      const transformOrigin = mousePosition
        ? `${mousePosition.x - elementOffset.left}px ${
            mousePosition.y - elementOffset.top
          }px`
        : '';
      // console.log('--onPrepare--mousePosition--transformOrigin--:', mousePosition, transformOrigin)
      if (transformOrigin) {
        setTransformOriginStyle({ transformOrigin });
      }
    }, 500);
  }

  //根据源码CSSMotion.tsx， motionChildren 存在时才能获取CSSMotion.props.children对应的dom
  // 而初始化open:false 时 portal没有加载Dialog组件，所以Content加载时，CSSMotion.visible === true, motionChildren一定有值
  // React.useEffect(() => {
  //   console.log('--content--useEffect--dialogRef.current--:', dialogRef.current)
  // }, [])

  // onAppearPrepare={onPrepare} ym-dialog-zoom-appear  ym-dialog-zoom-active  ym-dialog-zoom
  // onEnterPrepare={onPrepare} ym-dialog-zoom-appear  ym-dialog-zoom-active   ym-dialog-zoom
  //

  return (
    <CSSMotion
      visible={open}
      onVisibleChanged={(newVisible) => {
        onVisibleChanged(newVisible);
      }}
      onAppearPrepare={onPrepare}
      onEnterPrepare={onPrepare}
      // onAppearActive={(element, event) => {
      //   // console.log('--onAppearActive--element--event---:', element, event)
      //   // const elementOffset = element.getBoundingClientRect(); //left/top:距离视口的距离
      //   // console.log('--element--elementOffset--:', elementOffset);
      //   // onPrepare();
      // }}
      forceRender={forceRender}
      motionName={motionName}
      removeOnLeave={destroyOnClose} //动画结束时，卸载dom
      ref={dialogRef}
    >
      {/*CSSMotion--这个children是一个函数*/}
      {({ className: motionClassName, style: motionStyle }, motionRef) => (
        <Panel
          {...restProps}
          styles={styles}
          ariaId={ariaId}
          open={open}
          holderRef={motionRef}
          style={{ ...motionStyle, ...transformOriginStyle }} //width,transformOrigin
          className={motionClassName}
        />
      )}
    </CSSMotion>
  );
};

export default Content;
